import 'package:hive/hive.dart';
import 'package:uuid/uuid.dart';
import '../models/team_model.dart';
import 'chat_service.dart';
import 'service_locator.dart';

class TeamService {
  final Box<TeamModel> _teamBox = Hive.box<TeamModel>('teams');

  // 创建团队
  Future<TeamModel> createTeam({
    required String name,
    required String initiatorId,
    required DateTime departureDate,
    required int maxMembers,
    String description = '',
    required String backgroundImage,
  }) async {
    final uuid = Uuid();
    final team = TeamModel(
      id: uuid.v4(),
      name: name,
      initiatorId: initiatorId,
      departureDate: departureDate,
      maxMembers: maxMembers,
      description: description,
      backgroundImage: backgroundImage,
    );

    await _teamBox.put(team.id, team);
    return team;
  }

  // 获取团队
  TeamModel? getTeamById(String id) {
    return _teamBox.get(id);
  }

  // 更新团队
  Future<void> updateTeam(TeamModel team) async {
    await _teamBox.put(team.id, team);
  }

  // 删除团队
  Future<void> deleteTeam(String id) async {
    await _teamBox.delete(id);
  }

  // 获取所有团队
  List<TeamModel> getAllTeams() {
    return _teamBox.values.toList();
  }

  // 获取用户创建的团队
  List<TeamModel> getTeamsByInitiator(String userId) {
    return _teamBox.values.where((team) => team.initiatorId == userId).toList();
  }

  // 获取用户参与的团队
  List<TeamModel> getTeamsByMember(String userId) {
    return _teamBox.values
        .where((team) => team.memberIds.contains(userId))
        .toList();
  }

  // 加入团队
  Future<bool> joinTeam(String teamId, String userId) async {
    final team = getTeamById(teamId);
    if (team != null && team.addMember(userId)) {
      await updateTeam(team);
      return true;
    }
    return false;
  }

  // 退出团队
  Future<bool> leaveTeam(String teamId, String userId) async {
    final team = getTeamById(teamId);
    if (team != null && team.removeMember(userId)) {
      await updateTeam(team);
      return true;
    }
    return false;
  }

  // 添加样例团队数据（开发测试用）
  Future<void> createSampleTeams(List<String> userIds) async {
    if (_teamBox.isEmpty && userIds.isNotEmpty) {
      // 确保至少有5个用户来创建样例团队
      if (userIds.length >= 5) {
        // 团队1: Deep Blue Dream Chaser
        final team1 = await createTeam(
          name: 'Deep Blue Dream Chaser',
          initiatorId: userIds[0], // 第一个用户作为创建者
          departureDate: DateTime.now().add(Duration(days: 15)), // 15天后出发
          maxMembers: 6,
          description:
              'Exploring the beautiful coral reefs in the Great Barrier Reef. This is a beginner-friendly dive trip focused on underwater photography and marine life observation.',
          backgroundImage: 'assets/images/qunliao.png',
        );

        // 为团队1创建群聊
        await _createTeamGroupChat(
          team1,
          [userIds[0]], // 初始只有创建者
          'Deep Blue Dream Chaser Team',
        );

        // 团队2: Ocean Explorers
        final team2 = await createTeam(
          name: 'Ocean Explorers',
          initiatorId: userIds[1], // 第二个用户作为创建者
          departureDate: DateTime.now().add(Duration(days: 30)), // 30天后出发
          maxMembers: 4,
          description:
              'Advanced diving expedition to explore underwater caves and hidden marine ecosystems. Participants should have at least 20 logged dives and advanced certification.',
          backgroundImage: 'assets/images/qunliao.png',
        );

        // 添加成员到团队2
        await joinTeam(team2.id, userIds[2]);

        // 为团队2创建群聊
        await _createTeamGroupChat(
          team2,
          [userIds[1], userIds[2]], // 创建者和成员
          'Ocean Explorers Team',
        );

        // 团队3: Coral Reef Divers
        final team3 = await createTeam(
          name: 'Coral Reef Divers',
          initiatorId: userIds[3], // 第四个用户作为创建者
          departureDate: DateTime.now().add(Duration(days: 45)), // 45天后出发
          maxMembers: 6,
          description:
              'Conservation-focused diving trip to participate in coral reef restoration efforts. Learn about marine ecology while helping to plant new coral colonies.',
          backgroundImage: 'assets/images/qunliao.png',
        );

        // 添加成员到团队3
        await joinTeam(team3.id, userIds[0]);
        await joinTeam(team3.id, userIds[2]);
        await joinTeam(team3.id, userIds[4]);

        // 为团队3创建群聊
        await _createTeamGroupChat(
          team3,
          [userIds[3], userIds[0], userIds[2], userIds[4]], // 创建者和所有成员
          'Coral Reef Divers Team',
        );

        // 团队4: Underwater Photographers
        final team4 = await createTeam(
          name: 'Underwater Photographers',
          initiatorId: userIds[2], // 第三个用户作为创建者
          departureDate: DateTime.now().add(Duration(days: 60)), // 60天后出发
          maxMembers: 5,
          description:
              'Specialized trip for underwater photography enthusiasts. We will focus on macro photography techniques and capturing the vibrant colors of marine life.',
          backgroundImage: 'assets/images/qunliao.png',
        );

        // 为团队4创建群聊
        await _createTeamGroupChat(
          team4,
          [userIds[2]], // 初始只有创建者
          'Underwater Photographers Team',
        );
      }
    }
  }

  // 为团队创建群聊的辅助方法
  Future<void> _createTeamGroupChat(
    TeamModel team,
    List<String> memberIds,
    String groupName,
  ) async {
    try {
      final ChatService _chatService = getIt<ChatService>();
      // 创建团队群聊
      final chat = await _chatService.createChat(
        participantIds: memberIds,
        isGroupChat: true,
        groupName: groupName,
        groupAvatar: team.backgroundImage, // 使用团队背景图作为群聊头像
      );

      // 发送欢迎消息
      if (memberIds.isNotEmpty) {
        await _chatService.sendMessage(
          chatId: chat.id,
          senderId: team.initiatorId,
          content:
              'Welcome to the ${team.name} team chat! Our diving trip is scheduled for ${_formatDate(team.departureDate)}.',
        );
      }

      // 可以将群聊ID保存到团队数据中，方便后续关联
      team.chatId = chat.id;
      await updateTeam(team);
    } catch (e) {
      print('创建团队群聊失败: $e');
    }
  }

  // 日期格式化辅助方法
  String _formatDate(DateTime date) {
    return "${date.month}/${date.day}/${date.year}";
  }
}
